/**
 * 
 */
package trungsi.gea.photos.client

import javax.swing.JDialog
import javax.swing.ListCellRenderer
import javax.swing.JLabel
import javax.swing.JList
import javax.swing.DefaultComboBoxModel

import java.awt.BorderLayout as BL
import java.awt.FlowLayout as FL
import java.awt.Color
import java.awt.Component
import java.awt.event.ItemListener

import org.json.JSONObject

/**
 * @author trungsi
 *
 */
public class UploadDialog extends JDialog {

	def swingBuilder
	def service
	
	def selectedFolderLabel
	def foldersComboBox
	def folderNameField
	def filesPane
	
	def files = []
	
	def onUploadStart, onUploadFileStart
	
	UploadDialog(swingBuilder, service) {
		this.swingBuilder = swingBuilder
		this.service = service
		initGUI()
	}
	
	public void show() {
		foldersComboBox.model = getRemoteFolders()
		super.show()
	}
	
	void initGUI() {
		selectedFolderLabel = swingBuilder.label(id : 'selectedFolderLabel')
		foldersComboBox = swingBuilder.comboBox(id : 'foldersComboBox', renderer : new FolderListCellRenderer())
		folderNameField = swingBuilder.textField(id : 'folderNameField', columns : 10)
		filesPane = swingBuilder.scrollPane(id : 'filesPane')
		
		def panel = swingBuilder.panel {
            borderLayout()
            panel (constraints : BL.NORTH) {
                vbox {
                    panel {
                        flowLayout(alignment : FL.LEFT)
                        label("Selected folder : ")
                        label(selectedFolderLabel)
                    }
                    panel {
                        flowLayout(alignment : FL.LEFT)
                        label("Remote folder")
                        comboBox(foldersComboBox)
                    }
                    panel {
                        flowLayout(alignment : FL.LEFT)
                        label("Create new remote folder")
                        textField(folderNameField)
                    }
                }
            }
            scrollPane(filesPane)
            panel (constraints : BL.SOUTH) {
                flowLayout(alignment : FL.RIGHT)
                button('Upload', actionPerformed : this.&doUpload)
            }
        }
		
		this.add(panel)
	}
	
	def doUpload(event) {
		dispose()
        onUploadStart?.call(this)
        doUploadFiles()
	}
	
	def getRemoteFolders() {
		def folders = service.getRemoteFolders()
        return new DefaultComboBoxModel(folders.toArray())
    }
	
	void doUploadFiles() {
		swingBuilder.doOutside {
            def remoteFolder = getSelectedFolder()
			service.uploadFiles(files.clone(), remoteFolder, onUploadFileStart)
        }
    }
	
    def getSelectedFolder() {
        if (folderNameField.text) {
            return service.newRemoteFolder(folderNameField.text)
        } else {
            return foldersComboBox.selectedItem.id
        }
    }
    
    void setSelectedFolder(folder) {
    	selectedFolderLabel.text = folder.absolutePath
    	files.clear()
        def table = swingBuilder.tableLayout {
            folder.eachFile {file ->
                def suffix = file.name.indexOf('.') != -1 ? file.name[file.name.lastIndexOf('.')..-1].toLowerCase() : ''
                //println suffix
                if (suffix in ['.gif', '.jpg', '.jpeg', '.png']) {
                    tr {
                        td {
                            //widget(new ImagePanel(file))
                        }
                        td {
                            files << file
                            checkBox(new MyCheckbox(), text : file.name, selected : true, stateChanged : {
                                event ->
                                if (event.source.selected) {
                                    files << file
                                } else {
                                    files.remove(file)
                                }
                            } as ItemListener)
                        } 
                    }
                }
            }
        }
        filesPane.viewportView = table
    }
}

class FolderListCellRenderer extends JLabel implements ListCellRenderer {
    public MyCellRenderer() {
        setOpaque(true);
    }

    public Component getListCellRendererComponent(JList list,
                                                  Object value,
                                                  int index,
                                                  boolean isSelected,
                                                  boolean cellHasFocus) {
    	setText(value?.name)

        Color background;
        Color foreground;

        // check if this cell represents the current DnD drop location
        JList.DropLocation dropLocation = list.getDropLocation();
        if (dropLocation != null
                && !dropLocation.isInsert()
                && dropLocation.getIndex() == index) {

            background = Color.BLUE;
            foreground = Color.WHITE;

        // check if this cell is selected
        } else if (isSelected) {
            background = Color.RED;
            foreground = Color.WHITE;

        // unselected, and not the DnD drop location
        } else {
            background = Color.WHITE;
            foreground = Color.BLACK;
        };

        setBackground(background);
        setForeground(foreground);

        return this;
    }

}
